﻿////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <copyright>Copyright 2008-2011 Andreas Huber Doenni</copyright>
// Distributed under the GNU General Public License version 2 (GPLv2).
// See accompanying file License.txt or copy at http://phuse.codeplex.com/license.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

namespace Phuse.GetTestMessages
{
    using System;
    using System.Diagnostics.CodeAnalysis;
    using System.Globalization;
    using System.IO;
    using System.Net;

    using Phuse.IO;

    /// <summary>Downloads the test messages used for testing the Python MIME parser. The test messages are
    /// intentionally not checked into source control to avoid copyright issues associated with redistribution.
    /// </summary>
    internal static class Program
    {
        [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", Justification = "Test infrastructure, will not be localized.")]
        private static void Main()
        {
            const string RemoteFilePattern = "msg_{0:00}.txt";
            const string LocalFilePattern = "PythonMsg{0:00}.eml";
            string assemblyDirectory =
                Path.GetDirectoryName(typeof(Program).Assembly.ManifestModule.FullyQualifiedName);
            string destinationDirectory =
                Path.Combine(assemblyDirectory, "..", "..", "..", "Phuse.MimeTest", "PythonTestMessages");

            Console.WriteLine("Getting Python test messages...");

            Directory.CreateDirectory(destinationDirectory);

            for (int messageNumber = 1; messageNumber < 45; ++messageNumber)
            {
                var remoteFilename = string.Format(CultureInfo.InvariantCulture, RemoteFilePattern, messageNumber);
                var localFilename = string.Format(CultureInfo.InvariantCulture, LocalFilePattern, messageNumber);

                var path = Path.Combine(destinationDirectory, localFilename);

                if (!File.Exists(path))
                {
                    var request = WebRequest.Create(
                        "http://svn.python.org/view/*checkout*/python/trunk/Lib/email/test/data/" + remoteFilename);

                    // Surprisingly, the Python tests have LF-only line endings
                    using (var response = request.GetResponse())
                    using (var webStream = new FixLineEndingsStream(response.GetResponseStream()))
                    using (var fileStream = File.Create(path))
                    {
                        StreamHelper.Copy(webStream, fileStream, new byte[8192]);
                    }
                }
            }
        }
    }
}
